import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:getx/config/global/app_cache.dart';
import 'package:getx/models/domain/request/login_request.dart';
import 'package:getx/models/domain/response/user.dart';
import 'package:getx/network/app_api.dart';
import 'package:getx/network/dio_client.dart';
import 'package:getx/router/router_names.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginViewModel extends GetxController {
  ///form key
  final GlobalKey<FormState> loginFormKey = GlobalKey<FormState>();

  ///账号控制器
  late TextEditingController emailController;

  ///密码控制器
  late TextEditingController passwordController;

  @override
  void onInit() {
    super.onInit();
    emailController = TextEditingController();
    passwordController = TextEditingController();
  }

  /*{
  "email":"123",
  "password":"123",
  }*/

  void login() async {
    if (loginFormKey.currentState!.validate()) {
      LoginRequest loginRequest = LoginRequest(
        email: emailController.text,
        password: passwordController.text,
      );
      var response = await DioClient().post(
        AppApi.login,
        data: loginRequest.toJson(),
        openLoading: true,
      );
      var body = response.data;

      if (body['code'] == 200) {
        var data = jsonDecode(body["data"]);
        var account = data["account"];
        User user = User.fromJson(jsonDecode(account));
        var token = data['token'];
        AppCache appCache = Get.find<AppCache>();
        appCache.user(user);
        appCache.token(token);
        SharedPreferences preferences = Get.find<SharedPreferences>();
        preferences.setString('user', account);
        preferences.setString('token', token);
        Get.offAllNamed(RouterNames.main);
      } else {
        ///登录失败
      }
    }
  }

  String? validatorUserName(String? value) {
    String userName = (value ?? "").trim();
    if (userName.isEmpty) {
      return '邮箱不能为空';
    }
    if (userName.length < 6 || userName.length > 24) {
      return '邮箱长度不能少于6为或不能长于16为';
    }
    return null;
  }

  String? validatorPassword(String? value) {
    String password = (value ?? "").trim();
    if (password.isEmpty) {
      return '密码不能为空';
    }
    if (password.length < 6 || password.length > 16) {
      return '密码长度不能少于6为或不能长于16为';
    }
    return null;
  }

  @override
  void onClose() {
    emailController.dispose();
    passwordController.dispose();
    super.onClose();
  }
}
